<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 
      该页面需要经过微信授权

        base:
        https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9551c38135f5192e&redirect_uri=https%3A%2F%2Fwill.natapp4.cc%2Fhello.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect

        userinfo:
        https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9551c38135f5192e&redirect_uri=https%3A%2F%2Fwill.natapp4.cc%2Fhello.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
     -->

    <h1>Hello</h1>

    <script>
      // 1. 从URL地址，获取 code
      //    如果url地址没有 code 参数，可以认为该页面不是授权打开的
      const code = new URLSearchParams(window.location.search).get("code");
      console.log("code", "=== code");

      if (!code) {
        console.log("老六，你不是正常打开的");
      } else {
        // 2. 调用微信接口，获取 access_token
        //    PS: 正常应该是直接调用公司自己后端的接口，而不是直接去调用微信接口
        const url = `/api/sns/oauth2/access_token?appid=wx9551c38135f5192e&secret=3bd2edc541561c5716c87b89d790d435&code=${code}&grant_type=authorization_code`;
        fetch(url)
          .then((response) => response.json())
          .then((result) => {
            console.log("result", result);

            // 3. 获取用户信息
            const url2 = `/api/sns/userinfo?access_token=${result.access_token}&openid=${result.openid}&lang=zh_CN`;
            fetch(url2)
              .then((response) => response.json())
              .then((result) => {
                console.log("result ==== ", result);

                const img = document.createElement("img");
                img.src = result.headimgurl;
                img.style.width = "100px";
                img.style.height = "100px";
                document.body.append(img);

                const p = document.createElement("p");
                p.innerHTML = result.nickname + "|||" + result.openid;

                document.body.append(p);
              });
          });
      }
    </script>
  </body>
</html>
